import { action, makeObservable, observable } from 'mobx'
import { fetchLogin, fetchUserInfo } from '@/api/user'
import { setToken } from '@/utils/auth'
import { StoreKey } from '@/common/constants'
import { useStorage } from '@/hooks/common'

class User {
  constructor() {
    makeObservable(this)
  }

  @observable menus = []

  @action login = async (data: any) => {
    try {
      const response: any = await fetchLogin(data)
      const { token } = response

      setToken(token)

      return Promise.resolve(response)
    } catch (e) {
      return Promise.reject(e)
    }
  }

  @action getInfo = async (data?: any) => {
    try {
      const storage = useStorage()
      const user: any = await fetchUserInfo(data)

      storage.localSet({ path: 'info', value: user })

      return Promise.resolve(user)
    } catch (e) {
      return Promise.reject(e)
    }
  }

  @action logout = () => {
    localStorage.removeItem(StoreKey)
  }
}

export default new User()
